<script lang="ts" setup name="GoodsImage">
import { computed, ref } from 'vue'
import { useMouseInElement } from '@vueuse/core'

defineProps<{ images: string[] }>()

// 默认高亮的下标 激活当前激活项的下标
const active = ref(0)

// 放大镜效果:
// 1. 鼠标移入 原盒子(400*400) 中出现灰盒子, 右侧出现一个放大的盒子(400*400)
// 2. 放大盒子其实和原盒子大小的, 知识里面的图片是2倍
// 3. 鼠标移出 灰盒子 放大盒子 都要消失
// 4. 获取鼠标基于盒子的坐标, 应该减去一段距离, 然后设置给灰盒子的left top值
// 5. 灰盒子向右移动, 放大盒子里面的图片向左移动; 灰盒子向下移动, 放大盒子里面的图片向上移动;

// => 需要知道鼠标在目标元素内, 鼠标相对于目标元素的坐标
// 1. mouseenter mouseleave mousemove 事件
// 2. 组合式函数 @vueuse/core

const target = ref(null)
const { elementX, elementY, elementHeight, elementWidth, isOutside } =
  useMouseInElement(target)
const position = computed(() => {
  let x = elementX.value - 100
  let y = elementY.value - 100

  // 限制蒙层只能在盒子中显示
  if (x <= 0) x = 0
  if (y <= 0) y = 0
  if (x >= 200) x = 200
  if (y >= 200) y = 200
  return {
    x: x,
    y: y,
  }
})
</script>
<template>
  <div class="goods-image">
    <!--放大盒子 -->
    <div
      v-show="!isOutside"
      class="large"
      :style="[
        {
          backgroundImage: `url(${images[active]})`,
          backgroundPosition: `${-position.x * 2}px ${-position.y * 2}px`,
        },
      ]"
    ></div>

    <!-- 左侧的大盒子 -->
    <div class="middle" ref="target">
      <img :src="images[active]" alt="" />

      <!-- 显示的遮罩 -->
      <div
        class="layer"
        v-show="!isOutside"
        :style="{ left: position.x + 'px', top: position.y + 'px' }"
      ></div>
    </div>

    <!-- 右侧五个小盒子 -->
    <ul class="small">
      <li
        v-for="(item, index) in images"
        :key="item"
        :class="{ active: active === index }"
        @mouseenter="active = index"
      >
        <img :src="item" alt="" />
      </li>
    </ul>
  </div>
</template>

<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;

  z-index: 500;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
